<?php

namespace app\common\services;

use app\common\exceptions\ErrException;
use app\common\Facade\Log;

/**
 * 七牛云直播云
 */
class TxImService
{

    protected static $ownerid;

    /**
     * @var array
     */
    protected $config;

    /**
     * @var string
     */
    protected $tsl_api;

    /**
     * @var string
     */
    protected $sig;

    /**
     * @var string
     */
    protected $random;

    public function __construct()
    {
        $this->config  = ['im_sdkappid' => env('tencent.im_sdkappid'), 'im_sdksecret' => env('tencent.im_sdksecret'), 'im_admin' => env('tencent.im_admin')];
        $this->tsl_api = new \Tencent\TLSSigAPIv2($this->config['im_sdkappid'], $this->config['im_sdksecret']);
        $this->sig     = $this->tsl_api->genUserSig($this->config['im_admin']);
        $this->random  = mt_rand(0,4294967295);
    }

    /**
     * 自定义消息体
     * @param $action
     * @param $data
     * @param $title
     * @param $desc
     * @return array
     * @Function:buildData
     * @Date: 2022/11/10
     * @Time: 20:49
     */
    public function buildData($action, $data = [], $title='', $desc='')
    {
        $elem['MsgType'] = 'TIMCustomElem';
        $elem['MsgContent']['Desc'] = $desc;
        $elem['MsgContent']['Title'] = $title;
        $eledata['action'] = $action;
        if(!empty($data)){
            $eledata['data'] = $data;
        }
        $elem['MsgContent']['Data'] = json_encode($eledata);
        return $elem;
    }

    /**
     * 创建直播群(修改为临时会议群)
     * @param int    $member_id  用户ID
     * @param string $ownerid    群主UserId
     * @param string $groupid    自定义群组ID
     * @param string $type       群类型(固定为直播群)
     * @return mixed
     * @throws ErrException
     */
    public function createChatGroup(int $member_id, string $ownerid, string $groupid, string $type = "ChatRoom")
    {
        $api          = "https://console.tim.qq.com/v4/group_open_http_svc/create_group?sdkappid={$this->config['im_sdkappid']}&identifier={$this->config['im_admin']}&usersig={$this->sig}&random=x{$this->random}&contenttype=json";
        $req_data['Owner_Account'] = (string)$ownerid;
        $req_data['Type']          = $type;
        $req_data['Name']          = $groupid;
        $req_data['GroupId']       = $groupid;
        $res = json_decode(httpHelper($api, json_encode($req_data)), true);
        Log::info('腾讯IM创建群，返回结果：' . json_encode($res));
        return $res;
    }

    /**
     * 导入单个用户数据
     * @param string $uuid
     * @param $name
     * @param $avatar
     * @return mixed
     * @throws \Exception
     */
    public function importAccount(string $uuid, $name, $avatar = '')
    {
        $api                    = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid={$this->config['im_sdkappid']}&identifier={$this->config['im_admin']}&usersig={$this->sig}&random={$this->random}&contenttype=json";
        $req_data['Identifier'] = $uuid;
        $req_data['Nick']       = $name;
        $req_data['FaceUrl']    = $avatar;
        return json_decode(httpHelper($api, json_encode($req_data)), true);
    }

    /**
     * 通知群组成员
     * @param string $groupid
     * @param $elem
     * @return mixed
     * @Function:sendChatRoomMsg
     * @Date: 2022/11/10
     * @Time: 20:49
     * @throws \Exception
     */
    public function sendChatRoomMsg($groupid, $elem)
    {
        $api                    = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_msg?sdkappid={$this->config['im_sdkappid']}&identifier={$this->config['im_admin']}&usersig={$this->sig}&random={$this->random}&contenttype=json";
        $req_data['GroupId']    = $groupid;
        $req_data['MsgRandom']  = rand(1000000,9999999);
        $req_data['MsgBody'][0] = $elem;
        return json_decode(httpHelper($api,json_encode($req_data)),true);
    }

    /**
     * 发送单聊消息
     * @param string $touid
     * @param $elem
     * @param $timelife
     * @return mixed
     * @Function:sendMsg
     * @Date: 2022/11/10
     * @Time: 21:04
     * @throws \Exception
     */
    public function sendMsg(string $touid, $elem, $timelife = 604800)
    {
        $api                          = "https://console.tim.qq.com/v4/openim/sendmsg?sdkappid={$this->config['im_sdkappid']}&identifier={$this->config['im_admin']}&usersig={$this->sig}&random={$this->random}&contenttype=json";
        $req_data['SyncOtherMachine'] = 2;
        $req_data['To_Account']       = $touid;
        $req_data['MsgRandom']        = rand(1000000,9999999);
        $req_data['MsgTimeStamp']     = time();
        $req_data['MsgLifeTime']      = $timelife;
        $req_data['MsgBody'][0]       = $elem;
        return json_decode(httpHelper($api,json_encode($req_data)),true);
    }
    public function getHistoryMsg($groupid, $timelife = 604800)
    {
        $api                      = "https://console.tim.qq.com/v4/group_open_http_svc/group_msg_get_simple?sdkappid={$this->config['im_sdkappid']}&identifier={$this->config['im_admin']}&usersig={$this->sig}&random={$this->random}&contenttype=json";
        $req_data['GroupId']      = $groupid;
        $req_data['ReqMsgNumber'] = 10;
        return json_decode(httpHelper($api,json_encode($req_data)),true);
    }

    /**
     * 生成 UserSig
     * @param string $uuid
     * @return string
     * @Function:genUserSig
     * @Date: 2022/11/11
     * @Time: 13:56
     * @throws \Exception
     */
    public function genUserSig(string $uuid)
    {
        $api = new \Tencent\TLSSigAPIv2($this->config['im_sdkappid'], $this->config['im_sdksecret']);
        return $api->genUserSig($uuid);
    }

    /**
     * 群组自定义消息体
     * @param array $data
     * @return array
     * @Function:buildMessageBody
     * @Date: 2022/12/19
     * @Time: 19:34
     */
    public function buildMessageBody(array $data = [])
    {
        $msgBody = [
            'content'              => '',         // 消息体内容
            'isManager'            => 0,          // 是否是管理员(0.普通用户 1.管理员)
            'isSpeak '             => 0,          // 是否正常发言(0.正常发言 1.禁言中)
            'isBlack '             => 0,          // 是否拉黑(0.正常 1.拉黑)
            'type'                 => 1,          // 消息体类型(1、群组普通文本消息  2、禁言  3、取消禁言 4、拉黑 5、取消拉黑 6、设置管理员 7、取消设置管理员 8、暂停直播  9、结束直播 10、重新开播 11、特效 12、滚动广告显示 13、滚动广告关闭 14、机器人消息（系统文本消息，托儿，马甲）15、系统消息（无头像，无昵称的展示效果）16、直播间点赞数  17、直播间在线人数 18、修改直播间信息 19、剩余直播时长 20：设置标签  21：取消标签)
            'osType'               => 'service',  // 设备类型 (ios、Android、H5、wxapp、service)
            'toUserId'             => 0,          // 腾讯IM_USER(用户UUID)
            'specialEffectsUrl'    => '',         // 特效链接
            'adContent'            => '',         // 滚动广告内容
            'tagContent'           => '',         // 标签内容
            'giveLikeNumber'       => 0,          // 直播间点赞人数
            'onlineNumber'         => 0,          // 直播间在线人数
            'futureLiveTime'       => 0,          // 剩余直播时长
            'robotCommentUserInfo' => (object)[], // 马甲用户信息(type == 14时, 主播端与小程序端展示用户信息头像、昵称在此字段里面取值)
            'liveInfo'             => (object)[], // 修改直播间信息(type == 18时，小程序端同步更新直播间最新信息)
            'setTagContent'        => '',         // 标签信息（type == 20 || 21 时有值，服务端发，小程序用）
        ];

        foreach ($data as $key=>$value)
        {
            if (isset($msgBody[$key])) $msgBody[$key] = $value;
        }
        return $msgBody;
    }
	
	
	/**
	 * 批量发送单聊消息
	 * @param array $touids
	 * @param $elem
	 * @param int $timelife
	 * @return mixed
	 * @Function:sendMsg
	 * @Date: 2022/11/10
	 * @Time: 21:04
	 */
	public function sendBatchMsg(array $touids, $elem, $timelife = 604800)
	{
		$api                          = "https://console.tim.qq.com/v4/openim/batchsendmsg?sdkappid={$this->config['im_sdkappid']}&identifier={$this->config['im_admin']}&usersig={$this->sig}&random={$this->random}&contenttype=json";
		$req_data['SyncOtherMachine'] = 2;
		$req_data['To_Account']       = $touids;
		$req_data['MsgRandom']        = rand(1000000,9999999);
		$req_data['MsgTimeStamp']     = time();
		$req_data['MsgLifeTime']      = $timelife;
		$req_data['MsgBody'][0]       = $elem;
		return json_decode(httpHelper($api,json_encode($req_data)),true);
	}
	
	public function getImUserGroup($uuid)
	{
		$api                        = "https://console.tim.qq.com/v4/group_open_http_svc/get_joined_group_list?sdkappid={$this->config['im_sdkappid']}&identifier={$this->config['im_admin']}&usersig={$this->sig}&random={$this->random}&contenttype=json";
		$req_data['Member_Account'] = (string)$uuid;
		$req_data['Offset']         = 0;
		return json_decode(httpHelper($api,json_encode($req_data)),true);
	}
}
